package by.admonko.universaltesting.dataaccess.impl;

import java.util.Date;
import java.util.List;

import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.springframework.stereotype.Repository;

import by.admonko.universaltesting.dataaccess.TestResultDao;
import by.admonko.universaltesting.datamodel.Test;
import by.admonko.universaltesting.datamodel.TestResult;
import by.admonko.universaltesting.datamodel.TestResult_;
import by.admonko.universaltesting.datamodel.UserGroup;
import by.admonko.universaltesting.datamodel.UserTbl;

@Repository
public class TestResultDaoImpl extends AbstractDaoImpl<Integer, TestResult>
		implements TestResultDao {

	protected TestResultDaoImpl() {
		super(TestResult.class);

	}

	@Override
	public List<TestResult> getByUser(UserTbl user) {

		CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

		CriteriaQuery<TestResult> root = cBuilder.createQuery(TestResult.class);
		Root<TestResult> criteria = root.from(TestResult.class);

		root.select(criteria);

		root.where(cBuilder.equal(criteria.get(TestResult_.user), user));

		TypedQuery<TestResult> query = getEm().createQuery(root);
		List<TestResult> list = query.getResultList();
		return list;
	}

	@Override
	public List<TestResult> getByUserGroup(UserGroup userGroup) {
		CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

		CriteriaQuery<TestResult> root = cBuilder.createQuery(TestResult.class);
		Root<TestResult> criteria = root.from(TestResult.class);

		root.select(criteria);

		root.where(cBuilder.equal(criteria.get(TestResult_.usergroup),
				userGroup));

		TypedQuery<TestResult> query = getEm().createQuery(root);
		List<TestResult> list = query.getResultList();
		return list;
	}

	@Override
	public List<TestResult> getByTest(Test test) {
		CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

		CriteriaQuery<TestResult> root = cBuilder.createQuery(TestResult.class);
		Root<TestResult> criteria = root.from(TestResult.class);

		root.select(criteria);

		root.where(cBuilder.equal(criteria.get(TestResult_.test), test));

		TypedQuery<TestResult> query = getEm().createQuery(root);
		List<TestResult> list = query.getResultList();
		return list;
	}

	@Override
	public List<TestResult> getByDate(Date date) {
		CriteriaBuilder cBuilder = getEm().getCriteriaBuilder();

		CriteriaQuery<TestResult> root = cBuilder.createQuery(TestResult.class);
		Root<TestResult> criteria = root.from(TestResult.class);

		root.select(criteria);

		root.where(cBuilder.equal(criteria.get(TestResult_.testDate), date));

		TypedQuery<TestResult> query = getEm().createQuery(root);
		List<TestResult> list = query.getResultList();
		return list;
	}

}
